package com.xjoyt.pay.master.services;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.params.CompanyChannelPageParam;
import com.xjoyt.pay.master.po.CompanyChannel;
import com.xjoyt.pay.master.repository.CompanyChannelRepository;

@Service
public class CompanyChannelService extends AbstractService {

	@Autowired
	private CompanyChannelRepository repository;

	public PageResult<CompanyChannel> loadPage(PageParam<CompanyChannelPageParam> param) {

		return repository.loadPage(param);
	}

	public ExecuteResult<?> save(CompanyChannel param) {
		if (param.company == null || param.channel == null || StringUtils.isBlank(param.company.id)
				|| StringUtils.isBlank(param.channel.id)) {
			return ExecuteResult.fail("数据不存在");
		}

		repository.findAllByCompanyIdAndChannelId(param.company.id, param.channel.id)
				.forEach(item -> repository.delete(item));

		CompanyChannel companyChannel = new CompanyChannel();
		companyChannel.addedDate = new Date();
		companyChannel.company = param.company;
		companyChannel.channel = param.channel;
		repository.save(companyChannel);
		return ExecuteResult.ok();
	}

	public ExecuteResult<?> saveAuto(CompanyChannel entity) {

		return ExecuteResult.ok();
	}

	public ExecuteResult<?> delete(String id) {
		if (StringUtils.isBlank(id)) {
			return ExecuteResult.fail("id不能为空");
		}
		CompanyChannel entity = repository.findOne(id);
		if (entity == null) {
			return ExecuteResult.fail("商户通道不存在");
		}
		repository.delete(id);
		return ExecuteResult.ok();
	}

	public List<CompanyChannel> findAll() {
		return repository.findAll();
	}
}
